#  -*- coding: utf-8 -*-
#  @Time    : 2021/10/26 14:17
#  @Author  : super

import socket
import threading

def response(file_data, new_socket_client):
	# 响应行
	response_lines = "HTTP/1.1 200 OK\r\n"
	# 响应头
	response_header = "Server: BWS/1.0 www.baidu.com\r\n"
	# 响应体
	response_body = file_data

	# 封装到一起
	response = (response_lines + response_header + "\r\n").encode("gbk") + response_body
	new_socket_client.send(response)

def headding_requests(new_socket_client):
	# 客户端给服务端发送数据
	recv = new_socket_client.recv(4096)
	if len(recv) == 0 :
		print("客户关闭了浏览器....")
		new_socket_client.close()
		return

	path_name = recv.decode("gbk").split(" ", 2)
	print(path_name[1])
	print(type(recv.decode("gbk")))
	print(recv.decode("gbk"))

	if path_name[1] == "/" :
		path_name[1] = "/index.html"

	try :
		# 给客户端发送数据
		with open("static" + path_name[1], "rb") as file :
			file_data = file.read()

		response(file_data, new_socket_client)

	except Exception as e :
		# 给客户端发送数据
		with open("static/error.html", "rb") as file :
			file_data = file.read()
		response(file_data, new_socket_client)

	finally :
		# 关闭客户端链接
		new_socket_client.close()

def main():
	# 创建socket链接
	tcp_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

	# 设置端口号服用
	tcp_socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

	# 指定地址、端口
	tcp_socket_server.bind(("", 9091))

	# 创建链接请求数
	tcp_socket_server.listen(128)
	while True :
		# 等待客户建立链接
		new_socket_client, ip_ropt = tcp_socket_server.accept()
		# 当客户端和服务器建立连接程，创建子线程
		sub_thread = threading.Thread(target = headding_requests, args = (new_socket_client,))
		# 设置守护主线程
		sub_thread.setDaemon(True)
		# 启动子线程执行对应的任务
		sub_thread.start()


if __name__ == '__main__' :

	main()
